<?php
declare (strict_types = 1);
namespace app\api\controller;

use think\Request;
use think\Exception;
use app\BaseController;
use think\facade\{Log, Db};
use think\exception\ValidateException;

use app\api\validate\{OrderValidate, FinValidate, UsersValidate};

use app\api\model\{Users, OrderMoney, MoneyRule, FinanceRecord, UserShop, Admin};

class OrderMoneyController extends BaseController
{
    /**
	 * 充值数量列表
	 */
    public function money_rule_list()
    {
        $moneyRuleModel = new MoneyRule();
        $list = $moneyRuleModel->getList([], 0);

        if($list['code'] != 'ok'){
            $this->error_back($list['msg']);
        }

        $this->success_back('ok', $list['data']);
    }

    /**
	 * 余额充值
	 */
    public function pay_card()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(OrderValidate::class)->scene('pay_card')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $orderMoneyModel = new OrderMoney();

            $data['status']   = 1;  /** 待付款状态 */
            $data['price']    = 1 * $data['number'];  /** 总价 */
            $data['order_no'] = getOrderNumber('CZ');  /** 订单号 */

            $field = ['order_no', 'user_id', 'admin_id', 'remarks', 'price', 'status', 'number'];
            $flag = $orderMoneyModel->add($data, $field);

            if($flag['code'] != 'ok'){
                $this->error_back($flag['msg']);
            }

            $this->success_back('ok', $flag['data']);
        }
    }

    /**
     * 支付
     */
    public function pay_money()
    {
        $data = input('');

        // 验证数据
        try{
            validate(OrderValidate::class)->scene('pay_order')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $userModel = new Users();
        $adminModel = new Admin();
        $orderModel = new OrderMoney();

        $order_info = $orderModel->where(['id' => $data['order_id']])->find();
        $user_info  = $userModel->where(['id' => $order_info['user_id']])->find();

        $admin_info  = $adminModel->where(['id' => $order_info->getData('admin_id')])->find();

        $payData['openid']    = $user_info['openid'];  /** 用户openid */
        $payData['shopNo']    = $admin_info['shopNo'];
        $payData['termId']    = $admin_info['termId'];
        $payData['order_no']  = $order_info['order_no'];  /** 订单号 */
        $payData['total_fee'] = $order_info['price'];  /** 支付金额 */
        $payData['body']      = '余额充值';  /** 说明标题 */
        $payData['notify']    = 'notify_money';  /** 回调方法 */

        // $payController = new WxpayController();
        $payController = new LakalapayController($this->app);
        $res = $payController->pay($payData);

        if($res['code'] == 200){
            $this->success_back('操作成功', $res['sign']);
        }else{
            $this->error_back($res['return_msg']);
        }
    }

    /**
	 * 消费明细
	 */
    public function money_list()
    {
        if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(FinValidate::class)->scene('money_list')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $finModel = new FinanceRecord();

            $field = ['id', 'content', 'number', 'create_time'];
            $where = ['user_id' => $data['user_id'], 'admin_id' => $data['admin_id'], 'money_type' => 3];
            $list = $finModel->getList($where, 1, $data['curr'], $data['limit'], $field);

            if($list['code'] != 'ok'){
                $this->error_back($list['msg']);
            }

            $this->success_back('ok', $list['data']);
        }
    }

    /**
	 * 电子卡核销
	 */
    public function setCardMoney()
    {
        $data = input('post.');

        // 验证数据
        try{
            validate(UsersValidate::class)->scene('card_money')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        /** 需要支付的金额 */
        $pay_money = $data['number'];
        
        /** 店铺ID */
        $admin_id = $data['admin_id'];

        /** 用户店铺信息条件 */
        $shop_where = ['user_id' => $data['user_id'], 'admin_id' => $admin_id];

        /** 查询用户在该店铺的资产信息 */
        $userShopInfo   = Db::name('user_shop')->where($shop_where)->find();

        $userInfo = Db::name('users')->where(['id' => $data['user_id']])->find();

        if($userShopInfo['card_money'] < $pay_money){
            $this->error_back('余额不足');
        }

        /** 实例化消息提醒 */
        $newsController = new NewsController($this->app);

        Db::startTrans(); 
        try {
            if($pay_money > 0){
                /** 减去余额 */
                $card_money_flag = Db::name('user_shop')->where($shop_where)->dec('card_money', (int)$pay_money)->update();

                if(!$card_money_flag){
                    throw new Exception("余额扣除失败【" . $data['user_id'] . "】");
                }

                /** 写入财务记录 */
                $card_money_fin_flag = addFin($data['user_id'], $admin_id, 0, 8, 3, '-' . (int)$pay_money, '余额付款');

                if($card_money_fin_flag === false){
                    throw new Exception("会员扣除余额记录添加失败【" . $data['user_id'] . "】");
                }

                /** 增加用户在当前店铺的总消费 */
                $money_total_flag = Db::name('user_shop')->where(['user_id' => $data['user_id'], 'admin_id' => $admin_id])->inc('money_total', (int)$pay_money)->update();

                if($money_total_flag === false){
                    throw new Exception("更新会员店铺总消费【" . $data['user_id'] . "】");
                }
                
                /** 更新用户在当前店铺的星级 */
                $userShopModel = new UserShop();
                $userShopModel->setStar($data['user_id'], $admin_id);

                /** 获得直购奖的ID */
                $push_user_id = $data['to_user_id'] ? $data['to_user_id'] : $userInfo['pid'];

                if($push_user_id > 0){
                    /** 受益人在当前店铺的资产信息 */
                    $userPushShopInfo = Db::name('user_shop')->where(['user_id' => $push_user_id, 'admin_id' => $admin_id])->find();

                    if($userPushShopInfo && $userPushShopInfo['star_id'] > 0){
                        /** 查询受益人的直购奖比例 */
                        $push_money = Db::name('star')->where(['id' => $userPushShopInfo['star_id']])->value('bonus_ratio');

                        if($push_money > 0){
                            /** 增加受益人在当前店铺的佣金 */
                            $fst_money_flag = Db::name('user_shop')->where(['user_id' => $push_user_id, 'admin_id' => $admin_id])->inc('money', (int)$pay_money * $push_money)->update();
                            
                            if($fst_money_flag === false){
                                throw new Exception("更新会员佣金失败【" . $push_user_id . "】");
                            }
                            
                            /** 写入财务记录 */
                            $fst_fin_flag = addFin($push_user_id, $admin_id, 0, 8, 1, '+' . round($pay_money * $push_money, 2), '消费佣金');

                            if($fst_fin_flag === false){
                                throw new Exception("会员佣金记录添加失败【" . $push_user_id . "】");
                            }

                            /** 公众号消息提醒 */
                            $newsController->news_money($push_user_id, $data['user_id'], $data['goods_id'], round($pay_money * $push_money, 2));
                        }
                    }
                }
            }

            Db::commit();    
        }catch(Exception $e){
            Db::rollback();
            Log::write($e->getMessage());
            $this->error_back($e->getMessage());
        }

        /** 公众号消息提醒 */
        $newsController->news_money($data['user_id'], $data['admin_id'], $data['goods_id'], 2, $data['number']);
        $this->success_back('ok');
    }

    /**
	 * 福利金核销
	 */
    public function dec_money_gold()
    {
        $data = input('post.');

        /** 需要支付的金额 */
        $pay_money = $data['number'];
        
        /** 店铺ID */
        $admin_id = $data['admin_id'];

        /** 用户店铺信息条件 */
        $shop_where = ['user_id' => $data['user_id'], 'admin_id' => $admin_id];

        /** 查询用户在该店铺的资产信息 */
        $userShopInfo   = Db::name('user_shop')->where($shop_where)->find();

        $userInfo = Db::name('users')->where(['id' => $data['user_id']])->find();

        if($userShopInfo['money_gold'] < $pay_money){
            $this->error_back('余额不足');
        }

        /** 查询商品信息 */
        $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();

        /** 实例化消息提醒 */
        $newsController = new NewsController($this->app);
        
        Db::startTrans(); 
        try {
            /** 减去福利金 */
            $card_money_flag = Db::name('user_shop')->where($shop_where)->dec('money_gold', (int)$pay_money)->update();

            if(!$card_money_flag){
                throw new Exception("福利金扣除失败【" . $data['user_id'] . "】");
            }

            /** 一代受益人ID */
            $fst_pid = $userInfo['pid'];

            /** 一级分销佣金 */
            $fstMoney = round($goods_info['fst_rate'] * $pay_money, 2);

            /** 二级分销佣金 */
            $secMoney = round($goods_info['sec_rate'] * $pay_money, 2);

            if($fstMoney > 0){
                /** 一代受益人用户信息 */
                $userFstInfo = Db::name('users')->where(['id' => $fst_pid])->find();

                /** 一代受益人在当前店铺的资产信息 */
                $userFstShopInfo = Db::name('user_shop')->where(['user_id' => $fst_pid, 'admin_id' => $admin_id])->find();

                 /** 一级分销 */
                if($userFstShopInfo){
                    /** 增加一代受益人在当前店铺的佣金 */
                    $fst_money_flag = Db::name('user_shop')->where(['user_id' => $fst_pid, 'admin_id' => $admin_id])->inc('money', $fstMoney)->update();
                    
                    if($fst_money_flag === false){
                        throw new Exception("更新会员一级佣金失败【" . $fst_pid . "】");
                    }
                    
                    /** 写入财务记录 */
                    $fst_fin_flag = addFin($fst_pid, $admin_id, 0, 0, 1, '+' . $fstMoney, '会员一级佣金');

                    if($fst_fin_flag === false){
                        throw new Exception("会员一级佣金记录添加失败【" . $fst_pid . "】");
                    }

                    /** 公众号消息提醒 */
                    $newsController->news_money($fst_pid, $data['user_id'], $data['goods_id'], $fstMoney);

                    /** 二级分销 */
                    if($userFstInfo['pid'] > 0 && $secMoney > 0){
                        /** 二代受益人在当前店铺的资产信息 */
                        $userSecShopInfo = Db::name('user_shop')->where(['user_id' => $userFstInfo['pid'], 'admin_id' => $admin_id])->find();

                        if($userSecShopInfo){
                            /** 增加二代受益人在当前店铺的佣金 */
                            $sec_money_flag = Db::name('user_shop')->where(['user_id' => $userFstInfo['pid'], 'admin_id' => $admin_id])->inc('money', (int)$secMoney)->update();

                            if($sec_money_flag === false){
                                throw new Exception("更新会员二级佣金失败【" . $userFstInfo['pid'] . "】");
                            }

                            /** 写入财务记录 */
                            $fst_fin_flag = addFin($userFstInfo['pid'], $admin_id, 0, 0, 1, '+' . $secMoney, '会员二级佣金');

                            if($fst_fin_flag === false){
                                throw new Exception("会员二级佣金记录添加失败【" . $userFstInfo['pid'] . "】");
                            }

                            /** 公众号消息提醒 */
                            $newsController->news_money($userFstInfo['pid'], $data['user_id'], $data['goods_id'], $secMoney);
                        }
                    }
                }
            }

            Db::commit();
        }catch(Exception $e){
            Db::rollback();
            Log::write($e->getMessage());
            $this->error_back($e->getMessage());
        }

        /** 公众号消息提醒 */
        $newsController->news_money($data['user_id'], $data['admin_id'], $data['goods_id'], 2, $data['number']);
        $this->success_back('ok');
    }
}